package com.yidianyanglao.user.service.impl;

import com.yidianyanglao.common.bean.Notice;
import com.yidianyanglao.common.bean.Series;
import com.yidianyanglao.common.mapper.CommonMapper;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.enums.NoticeType;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.core.util.DigestUitl;
import com.yidianyanglao.core.util.Log;
import com.yidianyanglao.user.bean.LuckyTreeBean;
import com.yidianyanglao.user.bean.RecommRecord;
import com.yidianyanglao.user.bean.SeedDetailsBean;
import com.yidianyanglao.user.bean.UserBean;
import com.yidianyanglao.user.mapper.UserMapper;
import com.yidianyanglao.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/11/9.
 */
@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;
    @Resource
    private CommonMapper commonMapper;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = RuntimeException.class)
    @Override
    public String serviceTranscatiuon() {
        userMapper.addUserTest("123");
        System.out.println("1");
        System.out.println("1");
        userMapper.updateUserTest("1234456");
        System.out.println("1");
        List<String> list = userMapper.getList();
        for (String s:list){
            System.out.println("s:"+s);
        }
        System.out.println("1");
        return "";
        //throw new RuntimeException("异常");
    }

    @Transactional
    @Override
    public UserBean transferringSeed(String token,String touseraccount,double seednum) {

        UserBean fromUser = userMapper.getUserInfoByToken(token);
        UserBean toUser = userMapper.getUserByAccount(touseraccount);

        //种子数验证
        if(fromUser.getOrdinarySeed() < seednum){
            throw new CustomException(Code.ERROR,"种子数余额不足");
        }

        //普通种子总数 - 冻结种子数，如果小于当前转赠种子数，提示 ，当前有多少种子在冻结中
        if(fromUser.getOrdinarySeed()-fromUser.getFrozenSeed()<seednum){
            throw new CustomException(Code.ERROR,"当前有"+fromUser.getFrozenSeed()+"在冻结中，无法转赠");
        }

        //更新用户种子情况，包括，用户id，用户当前种子数，用户历史被赠送的种子数,用户种子和
        //更新赠送人
        fromUser.setOrdinarySeed(fromUser.getOrdinarySeed()-seednum);  //赠送方种子数
        int result = 0;
        result = userMapper.UpdateSeed(fromUser.getId(),fromUser.getOrdinarySeed(),fromUser.getGiveseed(),fromUser.getOrdinarySeedNum(),fromUser.getVersion());
        if(result <=0){
            throw new CustomException(Code.ERROR,"赠送人数据更新失败");
        }

        //更新获赠人
        toUser.setOrdinarySeed(toUser.getOrdinarySeed()+seednum);    //获赠人种子数
        toUser.setGiveseed(toUser.getGiveseed()+seednum);               //获赠人历史收到转赠数
        result = userMapper.UpdateSeed(toUser.getId(),toUser.getOrdinarySeed(),toUser.getGiveseed(),toUser.getOrdinarySeedNum(),toUser.getVersion());
        if(result <=0){
            throw new CustomException(Code.ERROR,"获赠人数据更新失败");
        }

        //产生转赠人记录
        //转赠人id，变化的种子数，变化后的种子数
        SeedDetailsBean fseedDetail = new SeedDetailsBean("普通","已转赠",fromUser.getId(),fromUser.getUsertype(),0f-seednum,fromUser.getOrdinarySeed(),fromUser.getId(),fromUser.getRealname(),toUser.getId(),toUser.getRealname());
        userMapper.addSeedDetailZz(fseedDetail);
        //获赠人记录，转赠人，获赠人
        SeedDetailsBean tseedDetail = new SeedDetailsBean("普通","已获赠",toUser.getId(),toUser.getUsertype(),seednum,toUser.getOrdinarySeed(),fromUser.getId(),fromUser.getRealname(),toUser.getId(),toUser.getRealname());
        userMapper.addSeedDetailZz(tseedDetail);

        //转赠通知
        Notice notice = new Notice(fromUser.getId(),fromUser.getRealname(),"您向"+toUser.getRealname()+"转赠了"+seednum+"颗种子", NoticeType.GIVENOTICE.getNum(),0);
        commonMapper.addNotice(notice);
        notice = new Notice(toUser.getId(),toUser.getRealname(),fromUser.getRealname()+"向您转赠了"+seednum+"颗种子",NoticeType.GIVENOTICE.getNum(),0);
        commonMapper.addNotice(notice);
        notice = null;

        return fromUser;
    }

    /**
     * 用户注册第三部，事务管理，更新支付密码，分配注册种子，记录推荐，记录消息，生成树
     * @param userBean
     */
    @Transactional
    @Override
    public void updatePayPass(String paypassword ,UserBean userBean) {

        //更新用户支付密码
        int result = userMapper.updatePayPwd(DigestUitl.MD5LowerCase(paypassword),userBean.getId());
        if(result<=0){
            throw new CustomException(Code.ERROR,"执行数据修改异常");
        }
        //更新用户注册奖励和通知
        userMapper.updateRegisteredSeed(userBean.getId());
        Notice notice = new Notice(userBean.getId(),userBean.getRealname(),"您已成功注册成为花匠，已获得10.0粒注册种子，将在您消费满500元并成功获得幸运树后自动激活，谢谢您的支持。", NoticeType.REWARD.getNum(),0);
        commonMapper.addNotice(notice);

        //查询推荐人，推荐人奖励和通知
        UserBean fromUser = userMapper.getUserInfo(userBean.getPmobile());
        // 推荐人获得10颗注册种子，关闭功能
        //userMapper.updateRegisteredSeed(userBean.getPid());
        //notice = new Notice(userBean.getPid(),userBean.getPname(),"您推荐的花匠"+userBean.getRealname()+"已成功注册，已获得10.0粒推荐种子，将在该花匠消费满500元并成功获得幸运树后自动激活，谢谢您的支持。", NoticeType.REWARD.getNum(),0);
        //commonMapper.addNotice(notice);
        if(fromUser != null){
            //推荐人id，被推荐人id，推荐人姓名，被推荐人姓名，推荐人用户类型，被推荐人用户类型
            RecommRecord recommRecord = new RecommRecord(fromUser.getId(),userBean.getId(),fromUser.getRealname(),userBean.getRealname(),fromUser.getUsertype(),userBean.getUsertype());

            if(userMapper.addRecomm(recommRecord)<=0){
                throw new CustomException(Code.ERROR,"记录推荐异常");
            }
        }

        List<Series> lists = userMapper.getSeries();

        for(Series series : lists){
            LuckyTreeBean luckyTreeBean = new LuckyTreeBean(series.getName(),series.getId(),userBean.getId(),series.getExchangeValue(),series.getConsumptionValue());
            userMapper.addLuckTree(luckyTreeBean);
        }

        //增加12系列树的规则

        //LuckyTreeBean luckyTreeBean = new LuckyTreeBean("12系列",1,userBean.getId(),500,297.5);

        //增加24系列树的规则
        //luckyTreeBean = new LuckyTreeBean("24系列",2,userBean.getId(),500,495);
        //userMapper.addLuckTree(luckyTreeBean);

        //记录种子明细 注册用户的明细
        SeedDetailsBean fseedDetail =new SeedDetailsBean("注册","注册奖励",userBean.getId(),userBean.getUsertype(),10,10);
        userMapper.addSeedDetailZz(fseedDetail);
        //记录推荐用户的种子明细，暂时关闭
//        fseedDetail =new SeedDetailsBean("注册","注册奖励",fromUser.getId(),fromUser.getUsertype(),10,fromUser.getRegisteredSeed()+10);
//        userMapper.addSeedDetailZz(fseedDetail);
    }

    @Transactional
    @Override
    public void updateMobileRelation(String token, String mobile) {

        UserBean userBean = userMapper.getUserInfoByToken(token);
        //先更新用户
        if(userMapper.updateUserMobile(mobile,token)<=0){
            throw new CustomException(Code.ERROR,"数据更新失败！");
        }
        //修改用户推荐记录
        userMapper.updateUserRecommendMobile(userBean.getId(),mobile);
        //修改订单推荐记录
        userMapper.updateOrderUsermobile(userBean.getId(),mobile);
    }

    @Override
    public void updateToken(int id) {
        String token = UUID.randomUUID().toString();
        if(userMapper.updateUserToken(id,token) <=0){
            throw new CustomException(Code.ERROR, "更新token异常！");
        }
    }
}
